<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\exam\model\admin\{Paper as PaperModel, PaperParts, QuestionTopicMaterial as Material};
use think\annotation\Inject;
use think\Model;

/**
 * Class Paper
 *
 * @package app\exam\logic\admin
 */
class Paper extends PaperModel
{

    /**
     * @Inject()
     *
     * @var PaperTopicLink
     */
    protected $paperTopicLinkLogic;

    /**
     * 获取列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/2
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $map = [])
    {
        return $this->where($map)->order('update_time', 'desc')->paginate($this->getListRows());
    }

    /**
     * 创建试卷
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/21
     *
     * @param array $data
     * @return bool
     */
    public function createPaper(array $data, $paperType = 1)
    {
        // 基础信息
        $baseInfo = [
            'title'               => $data['title'],
            'info'                => $data['info'],
            'category'            => $data['cate'],
            'fullcategorypath'    => $data['cate'],
            'paper_type'          => $paperType,
            'question_rand'       => $paperType == 2 ? 0 : $data['question_rand'],
            'answer_options_rand' => $data['answer_options_rand'],
            // 'start_time'          => ($data['exam_time'] && $data['exam_time'][0]) ? strtotime($data['exam_time'][0]) : 0,
            // 'end_time'            => ($data['exam_time'] && $data['exam_time'][1]) ? strtotime($data['exam_time'][1]) : 0,
            'total_time'          => $data['total_time'],
            // 'exam_number'         => $data['exam_number'],
            'visible_answer'      => $data['visible_answer'],
            'reviewer'            => $data['reviewer'] ?? 0
        ];
        // 解析部分数据
        $result                  = $this->parsePartsData($data['parts'], $paperType);
        $baseInfo['total_count'] = $result['total_count'];
        $baseInfo['total_score'] = $result['total_score'];
        $this->startTrans();
        try {
            if (!$this->save($baseInfo)) {
                throw new LogicException('新增试卷失败');
            }
            // 保存部分数据
            $partsData = $result['data'];
            $paperId   = $this->getAttr('id');
            $topics    = [];
            foreach ($partsData as $k => $v) {
                $partsData[$k]['paper_id'] = $paperId;
                if ($paperType == 1) {
                    $ids = array_column($v['value'], 'topic_id');
                    foreach ($ids as $id) {
                        $topics[] = [
                            'topic_id' => $id,
                            'paper_id' => $paperId
                        ];
                    }
                }
            }
            $parts = new PaperParts;
            $res   = $parts->replace()->saveAll($partsData);
            if (!$res) {
                throw new LogicException('新增试卷失败');
            }
            if (!empty($topics)) {
                // 记录试题引用详情
                $this->paperTopicLinkLogic->saveAll($topics);
            }
            // 试卷分类数量更新
            // PaperCategory::where('id', $baseInfo['cate'])->inc('num')->update();

            $this->commit();
            Log::write('新建试卷【' . $data['title'] . '】', 'exam', 'create', true);
            return true;
        } catch (LogicException $e) {
            $this->rollback();
            throw $e;
        } catch (\Exception $e) {
            $this->rollback();
        }

        throw new LogicException('新增试卷失败', $e->getMessage());
    }

    /**
     * 编辑试卷
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/22
     *
     * @param int   $id
     * @param array $data
     * @param int   $paperType
     * @return bool
     */
    public function editPaper(int $id, array $data, int $paperType = 1)
    {
        $paper                      = $this->findOrFail($id);
        $paper->title               = $data['title'];
        $paper->info                = $data['info'];
        $paper->paper_type          = $paperType;
        $paper->question_rand       = $paperType == 2 ? 0 : $data['question_rand'];
        $paper->answer_options_rand = $data['answer_options_rand'];
        // $paper->start_time          = ($data['exam_time'] && $data['exam_time'][0]) ? strtotime($data['exam_time'][0]) : 0;
        // $paper->end_time            = ($data['exam_time'] && $data['exam_time'][1]) ? strtotime($data['exam_time'][1]) : 0;
        $paper->total_time          = $data['total_time'];
        // $paper->exam_number         = $data['exam_number'];
        $paper->visible_answer      = $data['visible_answer'] ?? 0;
        $paper->reviewer            = $data['reviewer'] ?? 0;
        // 解析部分数据
        $result             = $this->parsePartsData($data['parts'], $paperType);
        $paper->total_count = $result['total_count'];
        $paper->total_score = $result['total_score'];

        $this->startTrans();
        try {
            if (!$paper->save()) {
                throw new LogicException('编辑试卷失败');
            }
            // 保存部分数据
            $partsData = $result['data'];
            $paperId   = $paper->getAttr('id');
            $topics    = [];
            foreach ($partsData as $k => $v) {
                $partsData[$k]['paper_id'] = $paperId;
                if ($paperType == 1) {
                    $ids = array_column($v['value'], 'topic_id');
                    foreach ($ids as $id) {
                        $topics[] = [
                            'topic_id' => $id,
                            'paper_id' => $paperId
                        ];
                    }
                }
            }
            // 写入部分数据
            $parts = new PaperParts;
            $parts->where('paper_id', $paperId)->delete();
            $res = $parts->saveAll($partsData);
            if (!$res) {
                throw new LogicException('编辑试卷失败');
            }
            // 先清空本试卷的试题记录
            if ($paperType == 1) {
                $this->paperTopicLinkLogic->clearLinks($paperId);
                if (!empty($topics)) {
                    // 记录试题引用详情
                    $this->paperTopicLinkLogic->saveAll($topics);
                }
            }

            $this->commit();

            Log::write('更新试卷【' . $data['title'] . '】', 'exam', 'update', true);

            return true;
        } catch (LogicException $e) {
            $this->rollback();
            throw $e;
        } catch (\Exception $e) {
            $this->rollback();
        }

        throw new LogicException('编辑试卷失败', $e->getMessage());
    }

    /**
     * 解析部分数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/21
     *
     * @param array $parts
     * @param int   $paperType
     * @return array
     */
    protected function parsePartsData(array $parts, int $paperType = 1)
    {
        if (empty($parts)) {
            throw new LogicException('请检查是否含有部分');
        }
        $result = [];
        switch ($paperType) {
            case 1:
                $totalScore = 0;// 总分数
                $totalCount = 0;// 总题数
                $data       = [];
                foreach ($parts as $k => $part) {
                    if(!count($part['scores'])) throw new LogicException('请设置分数');
                    $part['topics'] = $this->parsePartsValue1($part['topics'], $part['scores']);

                    $data[] = [
                        'number'      => $part['number'] ?? $k + 1,
                        'title'       => $part['title'] ?? '',
                        'description' => $part['description'] ?? '',
                        'value'       => $part['topics'],
                        'scores'      => $part['scores']
                    ];
                    $count  = count($part['topics']);
                    if ($count == 0) {
                        throw new LogicException('请检查部分中是否含有试题');
                    }
                    $totalCount += $count;
                    $totalScore += array_sum(array_column($part['topics'], 'score'));
                }
                $result = [
                    'total_count' => $totalCount,
                    'total_score' => $totalScore,
                    'data'        => $data
                ];
                break;
            case 2:
                $totalCount = 0;// 总题数
                foreach ($parts as $k => $part) {
                    if(!count($part['scores'])) throw new LogicException('请设置分数');
                    $data[] = [
                        'number'      => $part['number'] ?? $k + 1,
                        'title'       => $part['title'] ?? '',
                        'description' => $part['description'] ?? '',
                        'value'       => $part['banks'],
                        'scores'      => $part['scores']
                    ];
                    if (empty($part['banks'])) {
                        throw new LogicException('请检查部分中是否含有题库');
                    }
                    foreach ($part['banks'] as $bank) {
                        $count = array_sum($bank['topics']);
                    }

                    if ($count == 0) {
                        throw new LogicException('请检查部分中是否配置了题库的出题数量');
                    }
                    $totalCount += $count;
                }

                $result = [
                    'total_count' => $totalCount,
                    'total_score' => 0,
                    'data'        => $data
                ];
                break;
        }

        return $result;
    }

    /**
     * 固定卷试题信息
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-03-15
     *
     * @param  [type] $value  [description]
     * @param  [type] $scores [description]
     * @return [type]         [description]
     */
    public function parsePartsValue1($topics, $scores)
    {
        foreach ($topics as &$topic) {
            if (isset($topic['sub_topics'])) {
                foreach ($topic['sub_topics'] as &$sub) {
                    $sub = $this->_bindTopicScoreMiss($sub, $scores, 2);
                }
            } else {
                $topic = $this->_bindTopicScoreMiss($topic, $scores);
            }
        }

        return array_values($topics);
    }

    private function _bindTopicScoreMiss($topic, $scores, int $level = 1)
    {
        $mod           = $level == 1 ? app(QuestionTopic::class) : app(Material::class);
        $question_type = $mod->whereId($topic['topic_id'])->value('question_type');

        // 多选、不定项
        $score_miss = 0;
        if (in_array($question_type, [3, 4])) {
            $score_miss = $scores['question_type_' . $question_type . '_miss'] ?? 0;
            $score_miss = $score_miss > 0 ? round($topic['score'] * $score_miss / 100, 1) : 0;
        }
        $topic['score_miss'] = $score_miss;

        return $topic;
    }

    /**
     * 删除
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/21
     *
     * @param $ids
     */
    public function deletePapers($ids): void
    {
        $papers = $this->whereIn('id', (string)$ids)->selectOrFail();
        // 检查试卷是否被引用
        foreach ($papers as $paper) {
            // 是否被公开考试引用
            if (\app\exam\model\admin\ModuleExamination::where('paper_id', $paper->id)->value('id')) {
                throw new LogicException('试卷【' . $paper->title . '】已被引用到公开考试，无法删除');
            }
            // 是否被套卷引用
            if (\app\exam\model\admin\ModuleRollupPaper::where('paper_id', $paper->id)->value('id')) {
                throw new LogicException('试卷【' . $paper->title . '】已被引用到套卷练习，无法删除');
            }
        }
        $res = $papers->delete();
        if (!$res) {
            throw new LogicException('删除失败');
        }

        foreach ($papers as $paper) {
            Log::write('删除试卷【' . $paper->title . '】', 'exam', 'delete', true);
        }
    }

    /**
     * 获取试卷信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/22
     *
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPaperInfo(int $id)
    {
        $paper = $this->with(['paper_parts'])->findOrFail($id)->toArray();
        // 试卷部分数据解析
        $parts = $paper['paper_parts'];
        if ($parts) {
            foreach ($parts as &$part) {
                // 固定卷,解析试题
                if ($paper['paper_type'] == 1) {
                    // 查询试题
                    $topicIds = array_column($part['value'], 'topic_id');
                    $topics   = QuestionTopic::whereIn('id', $topicIds)->select()->each(function ($item) {
                        app(QuestionTopic::class)->paddingTopicData($item);
                    })->append(['question_type_text'])->toArray();
                    $topics   = array_column($topics, null, 'id');
                    foreach ($part['value'] as $k => $item) {
                        $part['value'][$k]['topic'] = $topics[$item['topic_id']];
                    }
                } else {
                    // 随机卷,解析题库
                    $bankIds = array_column($part['value'], 'bank');
                    $banks   = QuestionBank::whereIn('id', $bankIds)->select()->each(function ($item) {
                        $item->question_counts = app(QuestionBank::class)->getQuestionCount($item->getAttr('id'));
                    })->toArray();
                    $banks   = array_column($banks, null, 'id');
                    foreach ($part['value'] as $k => $item) {
                        $part['value'][$k]['bank'] = $banks[$item['bank']];
                    }

                }
            }
            unset($part);
            $paper['paper_parts'] = $parts;
        }

        return $paper;
    }

    /**
     * 更新单个字段
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/3/10
     *
     * @param int    $id
     * @param string $field
     * @param        $value
     * @return array|Model
     */
    public function editField(int $id, string $field, $value)
    {
        // 信息
        $paper = $this->findOrFail($id);

        $paper->$field = $value;

        if (!$paper->save()) {
            throw new LogicException("更新失败");
        }

        // 返回值
        return $paper;
    }

    /**
     * 获取试卷基础信息
     *
     * @param int $paperId
     * @return Paper|array|Model
     */
    public function getPaperBaseInfo(int $paperId)
    {
        return $this->where('id',$paperId)->findOrEmpty();
    }

}